import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../utils/agreement_manager.dart';

// 协议状态提供者 - 响应式管理
final agreementStatusProvider = StateNotifierProvider<AgreementStatusNotifier, bool>((ref) {
  return AgreementStatusNotifier();
});

// 协议状态管理器
class AgreementStatusNotifier extends StateNotifier<bool> {
  AgreementStatusNotifier() : super(false) {
    _loadAgreementStatus();
  }

  // 加载协议状态
  Future<void> _loadAgreementStatus() async {
    try {
      final hasAgreed = await AgreementManager.hasAgreed();
      state = hasAgreed;
    } catch (e) {
      print('加载协议状态失败: $e');
      state = false;
    }
  }

  // 设置协议同意状态
  Future<void> setAgreed(bool agreed) async {
    try {
      await AgreementManager.setAgreed(agreed);
      state = agreed;
    } catch (e) {
      print('设置协议状态失败: $e');
    }
  }

  // 刷新协议状态
  Future<void> refresh() async {
    await _loadAgreementStatus();
  }

  // 清除协议状态
  Future<void> clear() async {
    try {
      await AgreementManager.clear();
      state = false;
    } catch (e) {
      print('清除协议状态失败: $e');
    }
  }
}

// 协议检查提供者 - 用于应用启动检查
final agreementCheckProvider = FutureProvider<bool>((ref) async {
  final agreementNotifier = ref.read(agreementStatusProvider.notifier);
  await agreementNotifier.refresh();
  return ref.read(agreementStatusProvider);
}); 